<template>
  <n-modal
    v-if="showModal !== undefined"
    v-model:show="showModal"
    :mask-closable="false"
    :z-index="99"
    transform-origin="center"
  >
    <div class="w-120 p-4 bg-white">
      <div class="flex justify-between items-center">
        <h3 class="text-lg font-medium">{{ isRegister ? '注册' : '登录' }}</h3>
        <n-icon size="40" @click="closeModal">
          <CloseSharp />
        </n-icon>
      </div>

      <n-form ref="formRef" :rules="rules" :model="formData" class="login-form">
        <n-form-item label="账号" path="username">
          <n-input
            v-model:value="formData.username"
            placeholder="请输入账号"
            :disabled="isLoading"
          />
        </n-form-item>

        <n-form-item label="密码" path="password">
          <n-input
            v-model:value="formData.password"
            type="password"
            placeholder="请输入密码"
            :disabled="isLoading"
          />
        </n-form-item>

        <n-form-item v-if="isRegister" label="确认密码" path="confirmPassword">
          <n-input
            v-model:value="formData.confirmPassword"
            type="password"
            placeholder="请确认密码"
            :disabled="isLoading"
          />
        </n-form-item>

        <n-form-item>
          <n-button
            type="primary"
            block
            :loading="isLoading"
            attr-type="button"
            @click="handleSubmit"
          >
            {{ isRegister ? '注册' : '登录' }}
          </n-button>
        </n-form-item>
      </n-form>

      <n-button
        text
        @click="isRegister = !isRegister"
        class="toggle-btn"
        :disabled="isLoading"
      >
        {{ isRegister ? '已有账号？去登录' : '没有账号？去注册' }}
      </n-button>

      <!-- 错误提示 -->
      <n-alert
        v-if="errorMessage"
        type="error"
        show-icon
        :title="errorMessage"
        class="mt-4"
      />

      <!-- 滑块验证码组件 -->
      <div class="mt-4 flex justify-center">
        <SliderCaptcha ref="captchaRef" @verifySuccess="onVerifySuccess" />
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { CloseSharp } from '@vicons/ionicons5'
import { ref } from 'vue'
import { useUserStore } from '~/stores/user'
import type { FormInst, FormRules, FormItemRule } from 'naive-ui'
import { useMessage } from 'naive-ui'

const formRef = ref<FormInst | null>(null)
const isVerified = ref(false) // 验证状态
const showModal = ref(false)
const formData = ref({
  username: '',
  password: '',
  confirmPassword: ''
})
const isRegister = ref(false)
const captchaRef = ref<any>(null)
const isLoading = ref(false)
const errorMessage = ref('')
const message = useMessage()
const rules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码111',
      trigger: 'blur'
    },
    {
      required: true,
      message: '两次输入的密码不一致',
      trigger: 'blur',
      validator: (_rule: FormItemRule, value: string) => {
        return value === formData.value.password
      }
    }
  ]
}

const onVerifySuccess = () => {
  isVerified.value = true
  handleSubmit(null)
}

const handleSubmit = (e: MouseEvent | null) => {
  e?.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      // 验证验证码
      if (!isVerified.value) {
        // 未验证则打开验证码弹窗
        captchaRef.value?.open()
        return
      }
      return isRegister.value ? handleRegister() : handleLogin()
    } else {
      console.log(errors)
    }
  })
}

const handleLogin = async () => {
  isLoading.value = true
  errorMessage.value = ''

  try {
    const { data } = await $fetch<{ data: any }>('/api/login', {
      method: 'POST',
      body: {
        username: formData.value.username,
        password: formData.value.password
      }
    })
    console.log('登录响应:', data)

    // 存储用户信息
    const user = useUserStore()
    user.setUser(data.user)

    message.success('登录成功')
    showModal.value = false
    navigateTo('/my-music')
  } catch (error: any) {
    if (typeof error === 'object' && error !== null && 'data' in error) {
      const typedError = error.response as { _data: { statusMessage?: string } }
      // console.log(typedError,typedError._data)
      errorMessage.value = typedError._data?.statusMessage || '登录失败，请重试'
      console.log(errorMessage.value)
    } else if (error.status === 401) {
      errorMessage.value = '账号或密码错误'
    } else {
      errorMessage.value = '登录失败，请重试'
    }
  } finally {
    isLoading.value = false
  }
}

const handleRegister = async () => {
  isLoading.value = true
  errorMessage.value = ''

  try {
    if (formData.value.password !== formData.value.confirmPassword) {
      errorMessage.value = '两次输入的密码不一致'
      return
    }

    console.log('尝试注册:', formData.value.username)
    const { data } = await $fetch<{ data: any }>('/api/register', {
      method: 'POST',
      body: {
        username: formData.value.username,
        password: formData.value.password,
        confirmPassword: formData.value.confirmPassword
      }
    })
    console.log('注册响应:', data)

    message.success('注册成功，即将自动登录')
    await handleLogin()
  } catch (error) {
    console.error('注册错误:', error)
    if (typeof error === 'object' && error !== null && 'data' in error) {
      const typedError = error as { data: { statusMessage?: string } }
      errorMessage.value = typedError.data?.statusMessage || '注册失败，请重试'
    } else {
      errorMessage.value = '注册失败，请重试'
    }
  } finally {
    isLoading.value = false
  }
}

// 关闭窗口
const closeModal = () => {
  showModal.value = false
}

defineExpose({
  openModal: (val: boolean) => {
    showModal.value = val
  }
})
</script>

<style scoped>
.login-form {
  margin-bottom: 16px;
}

.toggle-btn {
  display: block;
  width: 100%;
  text-align: center;
  margin-top: 16px;
}
</style>
